<template>
    <div>
        <!-- 面包屑导航区域 -->
        <breadcrumb :nav-data="['商品管理','添加商品']"></breadcrumb>
        <!--        卡片区域-->
        <el-card>
            <!--            信息提示-->
            <el-alert title="添加商品信息" type="info" center :closable="false" show-icon>
            </el-alert>
            <!--            步骤条-->
            <el-steps :active="Number(activeIndex)" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!--            tab选项卡-->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
                <el-tabs tab-position="left" v-model="activeIndex" :before-leave="beforeTabChange" @tab-click="onTabClicked">
                    <el-tab-pane name="0" label="基本信息">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model.number="addForm.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model.number="addForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model.number="addForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <!--                    级联选择器-->
                            <el-cascader
                                v-model="addForm.goods_cat"
                                @change="onCascaderChange"
                                :options="cascaderOptions"
                                :props="cascaderProps"></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane name="1" label="商品参数">
                        <el-form-item v-for="item in manyTableData" :key="item.attr_id" :label="item.attr_name">
                            <el-checkbox-group v-model="item.attr_vals" size="small">
                                <el-checkbox v-for="(it, index) in item.attr_values" :key="index" :label="it" border></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane name="2" label="商品属性">
                        <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane name="3" label="商品图片">
                        <el-upload
                            :action="$http.defaults.baseURL+'upload'"
                            :headers="headers"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :on-success="onImgUploadSuccess"
                            :on-remove="handleRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-tab-pane>
                    <el-tab-pane name="4" label="商品内容">
                        <!-- 富文本编辑器组件 -->
                        <quill-editor v-model="addForm.goods_introduce"></quill-editor>
<!--                        添加商品按钮-->
                        <el-button type="primary" class="add_btn" @click="onAddGoods">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
    </div>
</template>

<script>
export default {
    name: "AddGoods",
    created() {
        console.log(this.$http.defaults.baseURL)
        this.getCategoriesData();
    },
    data() {
        return {
            checkboxGroup1: [],
            //步骤条被选中的index
            activeIndex: 0,
            //添加商品表单
            addForm: {
                goods_name: "",//商品名称
                goods_price: 0,//价格
                goods_weight: 0,//重量
                goods_number: 0,//数量
                goods_cat: [],//分类
                goods_introduce: "",//商品内容
                pics: [],//图片路径
                attrs: [],//动态参数和静态属性
            },
            //表单规则验证
            addFormRules: {
                goods_name: [
                    {required: true, message: '请输入商品名称', trigger: 'blur'},
                    {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
                ],
                goods_price: [
                    {required: true, message: '请输入商品价格', trigger: 'blur'},
                    {type: 'number', message: '商品价格必须为数字值'}
                ],
                goods_weight: [
                    {required: true, message: '请输入商品重量', trigger: 'blur'},
                    {type: 'number', message: '商品重量必须为数字值'}
                ],
                goods_number: [
                    {required: true, message: '请输入商品数量', trigger: 'blur'},
                    {type: 'number', message: '商品数量必须为数字值'}
                ],
                goods_cat: [
                    {required: true, message: '请输入商品分类', trigger: 'blur'},
                ],
            },
            //分类级联选择器
            cascaderOptions: [],
            //分类级联选择器配置项
            cascaderProps: {
                expandTrigger: 'hover',
                value: "cat_id",
                label: "cat_name",
                children: "children"
            },
            //商品动态参数数据
            manyTableData:[],
            //商品静态属性数据
            onlyTableData:[],
            //图片预览弹窗 图片地址
            dialogImageUrl: '',
            //图片预览弹窗隐藏显示
            dialogVisible: false,
            //上传图片插件请求头
            headers:{
                Authorization: window.sessionStorage.getItem('token')
            }
        }
    },
    methods: {
        //切换tab之前触发的回调函数
        beforeTabChange(activeName, oldActiveName) {
            //activeName 即将进入的标签的名字
            //oldActiveName 即将离开的标签的名字
            /*if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
                return Promise.reject(this.$message.error("请先选择商品分类！"))
            }*/
            if (oldActiveName === "0") {
                if (!this.addForm.goods_name) {
                    return Promise.reject(this.$message.error("请输入商品名称！"))
                }
                if (this.addForm.goods_cat.length !== 3) {
                    return Promise.reject(this.$message.error("请选择商品分类！"))
                }
            }
           /* if(activeName === "1"){

            }
            if(activeName === "2"){

            }*/
        },
        //tab选项卡被选中
        onTabClicked(){
            switch (this.activeIndex){
                case "1":{
                    this.getCategoriesAttrData("many")
                    break;
                }
                case "2":{
                    this.getCategoriesAttrData("only")
                    break;
                }
            }
        },
        //获取分类参数数据
        async getCategoriesAttrData(selStr) {
            if(this[selStr + 'TableData'].length !== 0) return;
            let {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
                params: {
                    sel: selStr
                }
            });
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
            if(selStr === "many"){
                res.data.forEach((item)=>{
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
                    item.attr_values = JSON.parse(JSON.stringify(item.attr_vals));
                })
            }
            this[selStr + 'TableData'] = res.data;
            console.log("获取分类参数数据====>",this[selStr + 'TableData'])
        },
        //获取分类数据
        async getCategoriesData() {
            let {data: res} = await this.$http.get("categories")
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
            this.cascaderOptions = res.data;
        },
        //分类级联选择器change事件
        onCascaderChange() {
            if (this.addForm.goods_cat.length !== 3) {
                this.addForm.goods_cat = [];
                return this.$message.warning("只能选择三级商品分类！")
            }
        },
        //图片上传成功后的回调函数
        onImgUploadSuccess(response){
            console.log(response);
            this.addForm.pics.push({
                pic: response.data.tmp_path
            })
        },
        //移除已上传图片的回调函数
        handleRemove(file, fileList) {
            console.log(file, fileList);
            //1.获取要删除图片的临时路径
            let filePath = file.response.data.tmp_path;
            //2.通过临时路径去找到当前图片在this.addForm.pics中的索引
            let deleteIndex = this.addForm.pics.findIndex(item => item.pic === filePath)
            //3.调用数组的splice方法,把当前图片信息从pics中删除
            this.addForm.pics.splice(deleteIndex, 1);
        },
        //点击预览图片回调函数
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        //点击添加商品按钮
        async onAddGoods(){
            console.log("点击添加商品按钮",this.addForm);
            let goodsForm = this.$utils.deepClone(this.addForm);
            goodsForm.goods_cat = goodsForm.goods_cat.join(",")
            //处理动态参数
            this.manyTableData.forEach((item)=>{
                goodsForm.attrs.push({
                    attr_id: item.attr_id,
                    attr_value: item.attr_vals.join(",")
                })

            })
            //处理静态属性
            this.onlyTableData.forEach((item)=>{
                goodsForm.attrs.push({
                    attr_id: item.attr_id,
                    attr_value: item.attr_vals
                })
            })
            console.log("点击添加商品按钮",goodsForm);
            let {data:res} = await this.$http.post("goods",goodsForm);
            console.log("点击添加商品按钮",res);
            if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
            this.$message.success(res.meta.msg);
            this.$router.push("/goods");
        }
    },
    computed:{
        //三级分类id
        cateId(){
            if(this.addForm.goods_cat.length === 3){
                return this.addForm.goods_cat[2]
            }
            return null;
        }
    }
}
</script>

<style scoped>
.el-steps {
    margin: 20px auto;
}

.el-step__title {
    font-size: 14px;
}
.add_btn{
    margin-top: 20px;
}
</style>